前言

透過處理瀏覽器事件、定時函式以及改善你的自訂 JavaScript 函式的組織及可重複利用性,藉此提升 jQuery 的效用。

圖片來源

 


 

用視窗物件控制定時的特效

每當訪客在瀏覽器裡打開新視窗時, window 物件就會被建立,並且提供許多 jQuery 和 JavaScript 的能力,在 JavaScript 的世界裡, window 物件是全域物件,換句話說, window 物件是 JavaScript 世界裡最上層的物件。

window.name
window 物件的內容特性,讓我們存取或設定視窗的名稱。

window.history
window 物件的內容特性,讓你存取視窗在一段時間以來已載入的不同 URL 。

window.document
window 物件的內容特性,參照到被載入文件的主要內容。

window.onfocus
偵測視窗何時接收到點擊,鍵盤輸入或其他某種輸入。

window.setTimeout()
window 物件的內容特性,用來設定「在呼叫函式或其他陳述式之前先等待一段期間」。

window.clearTimeout()
window 物件的內容特性,用來取消「一段等待期間」。

window.setInterval()
window 物件的內容特性,用來設定「在重複呼叫函式或其他陳述式之間的等待期間」。

window.clearInterval()
window 物件的內容特性,用來取消「重複之間的等待期間」。

window.onblur
偵測視窗何時失去焦點。

JavaScript 的 window 物件的 onblur / onfocus 事件處理器與 jQuery 的不同, jQuery 的 blur 與 focus 方法要附加在 HTML 表單欄位與其他元素上,而不是 window 物件。

window.onblur = blurResponse;
function blurResponse(){
    ...
}

 


 

定時器方法

jQuery 和 JavaScript 皆提供我們根據時間經過而呼叫函式的定時器方法, JavaScript 的 window 物件有四個定時器方法可調控函式呼叫的時機: setTimeout 、 clearTimeout 、 setInterval 、 clearInterval;而 jQuery 提供 delay ( 延遲 )方法。

setTimeout
使用於想要設定必須等待一段時間之後再叫函式執行時。

setTimeout(當暫停時間經過之後要呼叫的函式,暫停時間);

setTimeout(myFunction,4000);

clearTimeout
使用於想取消由 setTimeout() 方法設置的定時操作。

clearTimeout(傳遞變數作為參數);

myTimeout = setTimeout(myFunction,4000);
clearTimeout(myTimeout);

setInterval
使用於需要函式每隔一段時間反覆執行時。

setInterval(在每段時間間隔過後要重複執行的函式,反覆執行函式之間的時間間隔);

setInterval(repeatMe,2000);

clearInterval
使用於想取消由 setInterval() 方法設置的定時操作。

clearInterval(傳遞變數作為參數);

myInterval = setInterval(repeatMe,2000);
clearInterval(myInterval);

delay
使用於要在一連串特效間增加一段暫停時間時。

delay(暫停時間);

slideDown().delay(5000).slideUp();

 


 

參考資料

深入淺出 jQuery ( Ryan Benedetti, Ronan Cranley 著、楊仁和 譯 )


#jq #jq總務處 #jquery #深入淺出 jQuery #name #history #document #onfocus #setTimeout() #clearTimeout() #setInterval() #clearInterval() #onblur #delay







Related Posts

響應式RWD實作練習

響應式RWD實作練習

AWS Solutions Architect - Associate (SAA) 學習計畫與備考心得: Module 4

AWS Solutions Architect - Associate (SAA) 學習計畫與備考心得: Module 4

Day 3 - Update CSS Variables with JS

Day 3 - Update CSS Variables with JS


Comments